#pragma once

#include<unordered_map>
#include"util.hpp"
#include<sstream>
#include<vector>
namespace cloud {
	class DataMannger {
	private:
		std::string _backup_file;
		std::unordered_map<std::string, std::string> _table;
		void split(const std::string& str, const std::string& SEP, std::vector<std::string>* arr)
		{
			size_t beg = 0;
			size_t pos = str.find(SEP, beg);
			while(pos != str.npos)
			{
				if (pos == beg)
				{
					beg += SEP.size();
					pos = str.find(SEP, beg);

					continue;
				}

				arr->push_back(str.substr(beg, pos - beg));
				beg = pos + 1;
				pos = str.find(SEP, beg);

			}
			if (beg < str.size())
			{
				arr->push_back(str.substr(beg));
			}

		}
	public:
		DataMannger(const std::string& backup_file):_backup_file(backup_file) 
		{
			InitLoad();
		}
		bool Storage()
		{
			std::stringstream ss;
			for (const auto& p : _table)
			{
				ss << p.first << " " << p.second<<"\n";
			}
			Util::FileUtil f(_backup_file);
			f.SetContent(ss.str());
			return true;
		}
		bool InitLoad()
		{
			Util::FileUtil f(_backup_file);
			if (f.Exists() == false)
			{
				return true;
			}
			std::string body;
			f.GetContent(&body);
			std::vector<std::string> arr;
			split(body, "\n", &arr);
			for (const auto& s : arr)
			{
				std::vector<std::string> f;
				split(s, " ", &f);
				if (f.size() != 2) continue;
				_table[f[0]] = f[1];

			}
			return true;
		}
		bool Insert(const std::string& key, const std::string& val)
		{
			_table[key] = val;
			Storage();
			return true;
		}
		bool Updata(const std::string& key, const std::string& val)
		{
			_table[key] = val;
			Storage();
			return true;
		}
		bool GetOneByKey(const std::string& key, std::string* val)
		{
			auto one = _table.find(key);
			if (one == _table.end())
			{
				return false;
			}
			*val = one->second;
			return true;
		}
	};
}
